layui.use(['table', 'ax','laydate','admin'], function () {
    var $ = layui.$;
    var table = layui.table;
    var $ax = layui.ax;
    var laydate = layui.laydate;
    var admin = layui.admin;
    lay('.datetime-input,.date-input').each(function(){
        var dateType = "datetime";
        if(this.className.indexOf("datetime-input")<0){
            dateType = "date";
        }
        laydate.render({
            elem: this
            ,trigger: 'click'
            ,type: dateType
            ,range:true
            ,done:function(value,date,endDate){
                var realName = $(this.elem).attr("id").replace(/_$/gi,"");
                var dates = value.split(" - ");
                $("#"+realName).val(dates[0]);
                $("#"+realName+"End").val(dates[1]);
            }
        });
    });

    /**
     * 字典类型表管理
     */
    var IntegrateInfo = {
        tableId: "integrateInfoTable"
    };

    /**
     * 初始化表格的列
     */
    IntegrateInfo.initColumn = function () {
        return [[
            {type: 'checkbox',fixed:"left"},
            {type:'numbers',title:"序号",fixed:"left"},
            {field: 'id', hide: true, title: '编号'},

            {field: 'areaCode', sort: true, title: '地区代码',fixed:'left'}
            ,{field: 'area', sort: true, title: '地区名称'}
            ,{field: 'integrateType', sort: true, title: '积分类别',templet:function(d){return d.integrateTypeModel.name}}
            ,{field: 'wasteTypeId',sort:true,title:'垃圾类别',templet:function(d){return d.wasteTypeIdModel.typeName?d.wasteTypeIdModel.typeName:"不区分类别"}}
            ,{field: 'integrateVal', sort: true, title: '积分值'}
            ,{field: 'createTime', sort: true, title: '创建时间'}
            ,{field: 'userId', sort: true, title: '创建人',templet:function(d){return d.userIdModel.name}}
            ,{align: 'center', toolbar: '#tableBar', title: '操作',fixed:"right",minWidth:120}
        ]];
    };

    /**
     * 点击查询按钮
     */
    IntegrateInfo.search = function () {
        var queryData = {};
            queryData['areaCode'] = $("#areaCode").val();
            queryData['areaId'] = $("#areaId").val();
            queryData['integrateType'] = $("#integrateType").val();
            queryData['integrateVal'] = $("#integrateVal").val();
            queryData['wasteStationId'] = $("#wasteStationId").val();
            queryData['createTime'] = $("#createTime").val();
            queryData['createTimeEnd'] = $("#createTimeEnd").val();
            queryData['userId'] = $("#userId").val();
        table.reload(IntegrateInfo.tableId, {where: queryData,page:{curr: 1}});
    };

    /**
     * 弹出添加对话框
     */
    IntegrateInfo.openAddDlg = function () {
        admin.putTempData('formOk', false);
        top.layui.admin.open({
            type: 2,
            title: '添加',
            content: Feng.ctxPath + '/integrateInfo/add',
            area:"700px",
            end: function () {
                admin.getTempData('formOk') && table.reload(IntegrateInfo.tableId);
            }
        });
    };

    /**
     * 导出excel按钮
     */
    IntegrateInfo.exportExcel = function () {
        var checkRows = table.checkStatus(IntegrateInfo.tableId);
        if (checkRows.data.length === 0) {
            Feng.error("请选择要导出的数据");
        } else {
            table.exportFile(tableResult.config.id, checkRows.data, 'xls');
        }
    };
    IntegrateInfo.delItems = function () {
        var checkRows = table.checkStatus(IntegrateInfo.tableId);
        if (checkRows.data.length === 0) {
            Feng.error("请选择要删除的数据");
        } else {
            var datas = checkRows.data;
            var params = [];
            for(var i=0;i<datas.length;i++){
                params.push(datas[i].id);
            }
            var paramsJson = JSON.stringify(params);
            $.ajax({
                type:"POST",
                url: Feng.ctxPath + "/integrateInfo/delItems",
                dataType:"json",
                contentType:"application/json", // 指定这个协议很重要
                data:paramsJson,
                async:false,
                //只有这一个参数，json格式，后台解析为实体，后台可以直接用
                success:function(data){
                    Feng.success("删除成功!");
                    table.reload(IntegrateInfo.tableId);
                }
            })


        }
    };

    /**
     * 点击编辑
     *
     * @param data 点击按钮时候的行数据
     */
    IntegrateInfo.openEditDlg = function (data) {
        admin.putTempData('formOk', false);
        top.layui.admin.open({
            type: 2,
            title: '修改',
            area:"650px",
            content: Feng.ctxPath + '/integrateInfo/edit?id=' + data.id,
            end: function () {
                admin.getTempData('formOk') && table.reload(IntegrateInfo.tableId);
            }
        });
    };

    /**
     * 点击删除
     *
     * @param data 点击按钮时候的行数据
     */
    IntegrateInfo.onDeleteItem = function (data) {
        var operation = function () {
            var ajax = new $ax(Feng.ctxPath + "/integrateInfo/delete", function (data) {
                Feng.success("删除成功!");
                table.reload(IntegrateInfo.tableId);
            }, function (data) {
                Feng.error("删除失败!" + data.responseJSON.message + "!");
            });
            ajax.set("id", data.id);
            ajax.start();
        };
        Feng.confirm("是否删除?", operation);
    };

    // 渲染表格
    var tableResult = table.render({
        elem: '#' + IntegrateInfo.tableId,
        url: Feng.ctxPath + '/integrateInfo/list',
        page: true,
        height: "full-98",
        cellMinWidth: 100,
        cols: IntegrateInfo.initColumn(),
        done:function(res){
                var createTimeDates =  $("#createTime_").val();
                var createTimeDateParts = createTimeDates.split(" - ");
                if(createTimeDateParts.length==2){
                    $("#createTime").val(createTimeDateParts[0]);
                    $("#createTimeEnd").val(createTimeDateParts[1]);

                }
        }
    });

    // 搜索按钮点击事件
    $('#btnSearch').click(function () {
        var validation = new Validation($("form")[0], {onSubmit:false});
        var validate = validation.validate();
        if(validate){
            IntegrateInfo.search();
        }else{
            var serializeArray = $(".validation-failed");
            var errMsgs = "";
            for(var i=0;i<serializeArray.length;i++){
                var elemInfo = serializeArray[i];
                var elem = $("#"+elemInfo.name)[0];
                if(elem && elem.tooltip){
                    errMsgs+="<div><span style='color:dodgerblue'>"+elem.placeholder+"输入框有误：</span><span style='color:red'>"+elem.tooltip.content+"</span></div>"
                    var tipElem = elem.tagName=="SELECT"?$(elem).next():elem;
                    layer.tips(elem.tooltip.content,tipElem,{
                        tips: [1, '#FF99CC'],
                        time: 4000,
                        tipsMore: true
                    });
                }
            }
            //Feng.error(errMsgs);
        }
        return false;
    });

    // 添加按钮点击事件
    $('#btnAdd').click(function () {
        IntegrateInfo.openAddDlg();
        return false;
    });
    // 导出excel
    $('#btnExp').click(function () {
        IntegrateInfo.exportExcel();
        return false;
    });
    $('#btnDel').click(function () {
        IntegrateInfo.delItems();
        return false;
    });
    IntegrateInfo.onShow = function(data){
        top.layui.admin.open({
            type: 2,
            title: '查看',
            content: Feng.ctxPath + '/integrateInfo/show?id=' + data.id,
        });
    }

    // 工具条点击事件
    table.on('tool(' + IntegrateInfo.tableId + ')', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;

        if (layEvent === 'edit') {
            IntegrateInfo.openEditDlg(data);
        } else if (layEvent === 'delete') {
            IntegrateInfo.onDeleteItem(data);
        }else if(layEvent==='show'){
            IntegrateInfo.onShow(data);
        }
    });
});
